package one.stand.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.CategoryResponse;
import one.stand.mapper.GoodsApiShowroomMapper;
import one.stand.model.GoodsType;
import one.stand.model.ResultModel;
import one.stand.util.OneListUtil;
import one.stand.util.RequestContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author cjr
 */
@Api(description = "分类")
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private GoodsApiShowroomMapper goodsApiShowroomMapper;

    @ApiOperation(value = "商城-分类")
    @PostMapping
    @SecurityAuthCheck(company = true)
    public ResultModel<CategoryResponse> list() {
        final Integer companyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();
        List<GoodsType> goodstypeModels = goodsApiShowroomMapper.selectListByCompanyId(companyId);

        Map<Integer, Integer> parentIds = Maps.newHashMap();
        int i = 0;
        List<CategoryResponse.Category> categories = Lists.newArrayList();
        if (OneListUtil.isNotEmpty(goodstypeModels)) {
            CategoryResponse.Category category;
            CategoryResponse.Category categoryChild;
            for (GoodsType goodstypeModel : goodstypeModels) {
                if (goodstypeModel.getParentId() == 0) {
                    parentIds.put(goodstypeModel.getGoodstypeId(), i++);
                    category = CategoryResponse.Category.builder()
                            .id(goodstypeModel.getGoodstypeId())
                            .name(goodstypeModel.getName())
                            .children(Lists.newArrayList())
                            .build();
                    categories.add(category);
                } else {
                    categoryChild = CategoryResponse.Category.builder()
                            .id(goodstypeModel.getGoodstypeId())
                            .name(goodstypeModel.getName())
                            .build();
                    int parentIndex = parentIds.get(goodstypeModel.getParentId());
                    categories.get(parentIndex).getChildren().add(categoryChild);
                }
            }
        }

        CategoryResponse categoryResponse = CategoryResponse.builder()
                .categorys(categories)
                .build();
        return ResultModel.success(categoryResponse);
    }
}
